package com.golxen.framework.user;


import com.golxen.framework.CrossProtocol;
import com.golxen.framework.PBPacket.PBPacketUtils;
import com.golxen.framework.manager.TempMgr;
import com.golxen.framework.user.dao.UserBussiness;
import com.golxen.framework.user.dao.entity.UserInfo;
import com.golxen.framework.user.player.PlayerPb;
import com.golxen.framework.user.player.GamePlayerMgr;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class UserMgr extends TempMgr {

	private static Map<Long, UserInfo> userInfoMap;

	public static String K = "";
	public static long T = 0;

	/**
	 * 需要更新到跨服的数据
	 */
	private static Map<Long, UserInfo> needUpdateToCrossMap = new ConcurrentHashMap<>();

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean reloadData() {
		userInfoMap = UserBussiness.getUserInfoMap();
		return true;
	}


	public static UserInfo getUserInfo(long userId) {
		if (userId > 0) {
			UserInfo userInfo = userInfoMap.get(userId);
			if (null == userInfo) {
				userInfo = UserBussiness.getUserInfoByUserId(userId);
				if (null != userInfo) {
					userInfoMap.put(userId, userInfo);
				}
			}
			return userInfo;
		}
		return null;
	}


	public static long getLastLoginTime(long userId) {
		if (userInfoMap.get(userId) == null) {
			return 0;
		}
		return userInfoMap.get(userId).getLastLoginTime();
	}


	public static String getNickName(long userId) {
		UserInfo userInfo = getUserInfo(userId);
		if (null != userInfo) {
			return userInfo.getNickName();
		}
		return "";
	}

	/**
	 * 获取注册人数
	 * 
	 * @return
	 */
	public static int getRegisterNum() {
		return userInfoMap.size();
	}



	public static void addNeedUpdateToCrossMap(long userId, UserInfo userInfo) {
		synchronized (needUpdateToCrossMap) {
			if (userInfo != null) {
				needUpdateToCrossMap.put(userId, userInfo);
			}
		}
	}

	/**
	 * 批量更新玩家数据到跨服
	 */
	public static void updateUserInfoToCross() {
		synchronized (needUpdateToCrossMap) {
			for (UserInfo item : needUpdateToCrossMap.values()) {
				GamePlayerMgr.sendPacket(item.getUserId(), PBPacketUtils.buildMessage(
						CrossProtocol.C_CROSS_UPDATE_USER_BASE_INFO, PlayerPb.parsePlayerBaseTempMsg(item)));
			}
			needUpdateToCrossMap.clear();
		}
	}

	public static List<UserInfo> getUserInfoList() {
		return new ArrayList<>(userInfoMap.values());
	}

	public static void setUserInfo(UserInfo userInfo) {
		if (null == userInfo) {
			return;
		}
		userInfoMap.put(userInfo.getUserId(), userInfo);
	}
}
